<?php

class formsplugin extends WikiPlugin
{
	function formsplugin()
	{
		$this->add_filter('htmlform', 10, '/^.*$/se', array(&$this, 'formprocessing'));
	}

	function formprocessing($matches, &$wiki) 
	{
		global $db, $mwconfig;
		
		$content = $matches[0];
				
		$content = stripslashes($content);
		if(isset($wiki->redirect)) {
			$wiki->linksto[] = $wiki->redirect;
		}
		
		$contentkeym = $content;
		$contentkeym = preg_replace('/\\x02B([0-9a-f]){32}\\x02E/', '*rollup*', $contentkeym);
		$contentkeym = preg_replace('/[0-9]+/', '*number*', $contentkeym);
		$contentkey = md5($contentkeym);
		
		$formcontent = $content;
		$nparts = preg_split('/\\(:wizardpage((?:\\|)(.*))?:\\)/i', $formcontent);
		if(isset($_POST['_formdata_' .$contentkey])) {
			$formdata = $_POST['_formdata_' . $contentkey];
			extract(unserialize(base64_decode($formdata)));
			$formpage = $formpath[count($formpath) - 1];
		}
		else {
			$formpage = 0;
			$formpath = array(0);
			$formvalues = array();
		}

		if(count($formvalues) > 0) {
			//owd($formvalues, $formpath);
			foreach($formvalues as $pagenumber=>$formpg) if(in_array($pagenumber, $formpath)) foreach($formpg as $k => $v) $_POST[$k] = $v;
		}
		if(isset($_POST['_formsignature']) && ($_POST['_formsignature'] == $contentkey) && ((count($nparts)==1) || (isset($_POST['_Finish'])))) {
			if(isset($wiki->sorted)) {
				ksort($_POST);
			}
			if(isset($wiki->email) || isset($wiki->dump)) {
				$from = 'wiki@' . $_SERVER['HTTP_HOST'];
				$headers = "MIME-Version: 1.0\r\n" .
					"From: {$from}\r\n";
				switch($mwconfig->email_format) {
				case 'HTML':
					$message = "<div>A form submission was received from <a href=\"{$_SERVER['REQUEST_URI']}\">{$wiki->page_name}</a> on " . date('m/d/Y') . " at " . date('H:i:s') . "</div>\n";
					$message .= "<div>These are the values that were submitted:</div>\n";
					$message .= "<table cellspacing=\"0\" cellpadding=\"0\">\n";
					foreach($_POST as $field=>$value) {
						if($field{0} == '_') continue;
						$alt = ($alt == '')?'background-color:#EEEEEE;':'';
						$field = str_replace('_', ' ', $field);
						$message .= "<tr><th valign=\"top\" style=\"padding-bottom:5px;{$alt}\">{$field}</th><td valign=\"top\" style=\"padding:0px 0px 5px 10px;{$alt}\"><pre>";
						if(is_array($value)) {
							foreach($value as $k=>$v) {
								$message .= "<b>" . str_replace('_', ' ', $k) . ":</b>{$v}<br />\n";
							}
						}
						else {
							$message .= $value;
						}
						$message .= "</pre></td></tr>\n";
					}
					$message .= "</table>\n";
					$headers .= "Content-Type: text/html; charset=\"UTF-8\"\r\n";
					break;
				case 'text':
					$message = "A form submission was received from {$wiki->page_name} on " . date('m/d/Y') . " at " . date('H:i:s') . "\r\n";
					$message .= "These are the values that were submitted:\r\n";
					$message .= "\r\n";
					foreach($_POST as $field=>$value) {
						if($field{0} == '_') continue;
						$field = str_replace('_', ' ', $field);
						$pfields[$field] = $value;
						$message .= "{$field}: ";
						if(is_array($value)) {
							$message .= "\r\n";
							foreach($value as $k=>$v) {
								$message .= "    " . str_replace('_', ' ', $k) . ": {$v}\r\n";
							}
						}
						else {
							$message .= stripslashes($value) . "\r\n";
						}
					}
					$message .= "\r\n";
					$message .= "\r\n";
					//$headers .= "Content-Type: text/text; charset=\"UTF-8\"\r\n";
					break;
				}
				
				if(isset($wiki->subject)) {
					//$subject = preg_replace_callback('/%([^%]+)%/i', create_function('$m', '$_POST[$m[1]]') , $wiki->subject);
					$subject = preg_replace('/%([^%]+)%/e', '$pfields["\\1"]', $wiki->subject);
				}
				else {
					$subject = 'Form Submission:' . $wiki->page_name;
				}
				if(isset($_POST['Email'])) $headers .= "Reply-To: " . $_POST['Email'] . "\r\n";
				if(isset($wiki->replyto)) $headers .= "Reply-To: " . $_POST[$wiki->replyto] . "\r\n";
				if(isset($wiki->email)) {
					mail($wiki->email, $subject, $message, $headers);
				}
				if(isset($wiki->dump)) {
					$content = $wiki->rollup($message);
				}
				//die("FOOO" . $wiki->unroll($content));
			}
			if(isset($wiki->mailer)) {
				$from = 'wiki@' . $_SERVER['HTTP_HOST'];
				$headers = "MIME-Version: 1.0\r\n" .
					"From: {$from}\r\n";
				$nw = new wikiengine();
				$message = strip_tags($nw->getpage($wiki->mailer, $pagerow));
				foreach($_POST as $field=>$value) {
					if($field{0} == '_') continue;
					$field = str_replace('_', ' ', $field);
					$pfields[$field] = $value;
					$message = str_replace("%{$field}%", $value, $message);
				}
				$message .= "\r\n";
				//$headers .= "Content-Type: text/text; charset=\"UTF-8\"\r\n";
				if(isset($wiki->subject)) {
					//$subject = preg_replace_callback('/%([^%]+)%/i', create_function('$m', '$_POST[$m[1]]') , $wiki->subject);
					$subject = preg_replace('/%([^%]+)%/e', '$pfields["\\1"]', $wiki->subject);
				}
				else {
					$subject = 'Form Submission:' . $wiki->page_name;
				}			
				mail($_POST[$wiki->replyto], $subject, $message, $headers);
			}
			if(isset($wiki->vtable)) {
				$new_session = $db->get_var("SELECT max(v_session) FROM {$mwconfig->db_tableprefix}formdata");
				$new_session = ((integer)$new_session) + 1;
				foreach($_POST as $k => $v) {
					if($k{0} == '_') continue;
					list($ek, $ev) = $db->escape($k, $v);
					$qry = "INSERT INTO {$mwconfig->db_tableprefix}formdata (v_session, v_table, v_field, v_value) values(";
					$qry .= "{$new_session}, '{$wiki->vtable}', '{$k}', '{$v}');";
					$db->query($qry);
					//owd("VTable", $qry, $db->get_error());
				}
			}
			if(isset($wiki->redirect)) {
				header('location:' . str_replace('%20', '+', urlencode($wiki->redirect)));
				die();
			}
			return $content;
		}

		if(count($nparts) > 1) {
			preg_match_all('/\\(:wizardpage((?:\\|)(.*))?:\\)/i', $formcontent, $settings);	
			$i = 0;
			foreach($nparts as $part) {
				$parts[] = array($part, (isset($settings[1][$i-1])?preg_replace('/&#([0-9]+);/e','chr(\\1)',trim($settings[1][$i-1], '|')):''));
				$i++;
			}
			if(isset($_POST['_Previous'])) {
				array_pop($formpath);
				if(count($formpath) > 0) {
					$formpage = $formpath[count($formpath) - 1];
				}
				else {
					$formpage = 0;
				}
			}
			if(isset($_POST['_Next'])) {
				foreach($_POST as $k => $v) {
					if($k{0} != '_') $formvalues[$formpage][$k] = $v;
				}
				do {
					$formpage++;
					$allowedfunctions = array(
						'strtolower'=>'strtolower',
						'gettabledata'=>'$wiki->gettabledata',
					);
					$ev = preg_replace('#\$([a-z_0-9]+)#i', '\\$_POST["\\1"]', $parts[$formpage][1]);
					$ev = preg_replace('/([a-z_]+)(?=\\s*(\\([^)]*\\)))/ie', '$allowedfunctions["\\1"]', $ev);
					$ev = str_replace(';', '', $ev);
					//$ev = preg_replace('#\$([a-z_0-9]+)#i', 'return "\\1"', $parts[$formpage][1]);
					if($ev == '') {
						$res = true;
					}
					else {
						$ev = "\$res = ({$ev})?true:false;";
						//owd($ev);
						eval($ev);
					}
					//owd($_REQUEST["pageoption"], $ev, $res, $_POST);
				} while (!($res || ($formpage > count($parts))));
				$formpath[] = $formpage;
			}

			//owd($formpage);			
			$formdata = base64_encode(serialize(compact('formpath','formvalues')));
			
			$formcontent = $parts[$formpage][0];
			$formcontent .= '<input type="hidden" name="_formdata_' . $contentkey . '" value="' . $formdata . '" />';
			if($formpage > 0)	$formcontent .= '<input type="submit" class="wikiwizard previous" name="_Previous" value="&laquo; Previous" />';
			$is_finished = ($formpage == count($parts) - 1) || strstr($formcontent, '%formfinish%');
			$is_cancelled = strstr($formcontent, '%formcancel%');
			$formcontent = preg_replace('#%formcancel%|%formfinish%#', '', $formcontent);
			foreach($formvalues as $fv) foreach($fv as $k=>$v) $flatten[$k] = $v;			

			if(preg_match('#%postpass:([^:]+):([^%]+)%#i', $formcontent, $m2)) {
				$is_postpass = !(isset($flatten[$m2[1]]) && ($flatten[$m2[1]] == $m2[2]));
				$formcontent = preg_replace('#%postpass:([^:]+):([^%]+)%#i', '', $formcontent);
			}
			else {
				$is_postpass = false;
			} 
			
			if($is_postpass) {
				$formcontent = "You need to provide a valid password to view this page.";
			}
			else {
				$formcontent = preg_replace('#%([a-z\s0-9_\-]+)%#ie', '$flatten["\\1"]', $formcontent);
				if(!$is_cancelled) {
					if($is_finished) {
						$formcontent .= '<input type="submit" class="wikiwizard finish" name="_Finish" value="Finish" />';
					}
					else {
						$formcontent .= '<input type="submit" class="wikiwizard next" name="_Next" value="Next &raquo;" />';
					}
				}
			}
		}
		$wiki->flags['formflag1'] = 'nofootnotes';
		$formcontent = $wiki->process($formcontent);
		unset($wiki->flags['formflag1']);

		$content = '<form method="post">
		<input type="hidden" name="_formsignature" value="' . $contentkey . '" />
		' . $formcontent . '
		</form>';

		return $content;
	} 

}

?>